from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseForbidden
from django.contrib.auth.models import User
from django.template import RequestContext

from django.views.generic.list_detail import object_list

from django.forms.formsets import formset_factory

from pypsqueak.profile.models import *
from pypsqueak.profile.forms import *
from pypsqueak.chrome.models import add_model_chrome
from pypsqueak.chrome.forms import ChromeBreadcrumbForm

def read( request, username ):
	""" Return a single profile """

	user = get_object_or_404(User, username=username)
	profile = add_model_chrome(user.get_profile(),request)

	if not profile.permission(request.user,'select'):
		return HttpResponseForbidden()

	# Load breadcrumb of parent pages.
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(user.get_absolute_url(),user.first_name)
	breadcrumb.append(profile.get_absolute_url,'Profile')


	return render_to_response( 'profile/profile_detail.html', locals(),
							context_instance=RequestContext(request) )


def list( request ):
	""" Return the list of users with their profiles """

	user_list = User.objects.all()

	return object_list( request,
		queryset=user_list,
		template_name="profile/profile_list.html",
		paginate_by=30,
		extra_context={ 'request': request } )


@login_required
def update( request, username ):
	""" Return a view for updating an profile """

	user = get_object_or_404(User, username=username )
	profile = user.get_profile()

	if not profile.permission(request.user,'update'):
		return HttpResponseForbidden()

	if request.method == 'POST':
		form = UserProfileUpdateForm(request.POST, request.FILES, instance=profile)
		if form.is_valid():
			profile = form.save()
			request.user.message_set.create(message='Profile updated')
			return HttpResponseRedirect( user.get_absolute_url() )
	else:
		form = UserProfileUpdateForm(instance=profile)

	# Load breadcrumb of parent pages.
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(user.get_absolute_url(),user.first_name)
	breadcrumb.append(profile.get_absolute_url,'Update Profile')

	return render_to_response('profile/profile_update.html', locals(),
							context_instance=RequestContext(request) );
